module repository.UserRepo;

import d2sqlite3;
import model.User;
import utils.ConstValue;

class UserRepo
{
    Database db;
    this ()
    {
        db = Database(Const.connStr);
    }

    ~this ()
    {
        db.close();
    }

    /** 
     * 获取一个用户，使用id
     * Params:
     *   userid  =  `uint`  =  用户id
     * Returns: 
     */
    User getOneUser (uint userid)
    {
        Statement statement = db.prepare(
            "SELECT id, username, nickname, role FROM user WHERE id=:id LIMIT 1");
        statement.bind(":id", userid);
        ResultRange results = statement.execute();
        scope (exit)
        {
            statement.reset();
        }
        if (results.empty)
        {
            return null;
        }
        auto row = results.front;
        auto id = row["id"].as!uint;
        auto username = row["username"].as!string;
        auto nickname = row["nickname"].as!string;
        auto role = row["role"].as!uint;

        return new User(id, username, nickname, role);
    }

    /** 
     * 获取一个用户，使用用户名和密码
     * Params:
     *   username  =  `string`  =  用户名
     *   password  =  `string`  =  密码
     * Returns: User
     */
    User getOneUser (string username, string password)
    {
        Statement statement = db.prepare(
            "SELECT u.id, u.username, u.nickname, u.role FROM user as u WHERE u.username=:username AND u.password=:password LIMIT 1");
        statement.bind(":username", username);
        statement.bind(":password", password);
        ResultRange results = statement.execute();
        scope (exit)
        {
            statement.reset();
        }
        if (results.empty)
        {
            return null;
        }
        auto row = results.front;
        auto id = row["id"].as!uint;
        auto uname = row["username"].as!string;
        auto nname = row["nickname"].as!string;
        auto role = row["role"].as!uint;

        return new User(id, uname, nname, role);
    }

    /** 
     * 获取一个用户，使用用户名
     * Params:
     *   username   =  `string`  =  用户名
     * Returns: User
     */
    User getOneUser (string username)
    {
        Statement statement = db.prepare(
            "SELECT u.id, u.username, u.nickname, u.role FROM user as u WHERE u.username=:username LIMIT 1");
        statement.bind(":username", username);
        ResultRange results = statement.execute();
        scope (exit)
        {
            statement.reset();
        }
        if (results.empty)
        {
            return null;
        }
        auto row = results.front;
        auto id = row["id"].as!uint;
        auto uname = row["username"].as!string;
        auto nname = row["nickname"].as!string;
        auto pwd = row["password"].as!string;
        auto role = row["role"].as!uint;

        return new User(id, uname, pwd, nname, role);
    }
}
